package com.rytx.web.controller.tool;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.diagnosis.DiagnosisUtils;
import com.alipay.api.domain.AlipayFundAuthOperationDetailQueryModel;
import com.alipay.api.domain.AlipayFundAuthOrderAppFreezeModel;
import com.alipay.api.domain.PostPayment;
import com.alipay.api.request.AlipayFundAuthOperationCancelRequest;
import com.alipay.api.request.AlipayFundAuthOperationDetailQueryRequest;
import com.alipay.api.request.AlipayFundAuthOrderAppFreezeRequest;
import com.alipay.api.response.AlipayFundAuthOperationCancelResponse;
import com.alipay.api.response.AlipayFundAuthOperationDetailQueryResponse;
import com.alipay.api.response.AlipayFundAuthOrderAppFreezeResponse;
import com.rytx.common.core.controller.BaseController;
import com.rytx.common.core.domain.R;
import com.rytx.common.utils.StringUtils;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * swagger 用户测试方法
 *
 * @author rytx
 */
@Api("用户信息管理")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController {
    private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();

    {
        users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
        users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
    }

    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public R<List<UserEntity>> userList() {
        List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
        return R.ok(userList);
    }

    @ApiOperation("获取用户详细")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
    @GetMapping("/{userId}")
    public R<UserEntity> getUser(@PathVariable Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            return R.ok(users.get(userId));
        } else {
            return R.fail("用户不存在");
        }
    }

    @ApiOperation("新增用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping("/save")
    public R<String> save(UserEntity user) {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
            return R.fail("用户ID不能为空");
        }
        users.put(user.getUserId(), user);
        return R.ok();
    }

    @ApiOperation("更新用户")
    @PutMapping("/update")
    public R<String> update(@RequestBody UserEntity user) {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
            return R.fail("用户ID不能为空");
        }
        if (users.isEmpty() || !users.containsKey(user.getUserId())) {
            return R.fail("用户不存在");
        }
        users.remove(user.getUserId());
        users.put(user.getUserId(), user);
        return R.ok();
    }

    @ApiOperation("支付宝创建免押订单")
    @PostMapping("/create")
    public R<String> zhifubao() throws AlipayApiException {

        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
        AlipayFundAuthOrderAppFreezeModel model = new AlipayFundAuthOrderAppFreezeModel();

        // 设置后付费项目
        // 创建一个PostPayment类型的列表
        List<PostPayment> postPayments = new ArrayList<PostPayment>();
        // 创建一个PostPayment类型的对象
        PostPayment postPayments0 = new PostPayment();
        // 设置对象的金额为0.01
        postPayments0.setAmount("0.01");
        // 设置对象的名称 为租金
        postPayments0.setName("租金");
        // 设置对象的描述 为2元/小时，99元封顶
        postPayments0.setDescription("2元/小时，99元封顶");
        // 将对象添加到列表中
        postPayments.add(postPayments0);
        // 将列表设置到模型中
        model.setPostPayments(postPayments);

        // 设置订单标题
        model.setOrderTitle("XX租车押金");

        // 设置需要冻结的金额
        model.setAmount("0.01");

        // 设置收款账户的支付宝用户号
        model.setPayeeUserId("2088102000275795");

        // 设置商户授权资金订单号
        model.setOutOrderNo("8077735255938023");

        // 设置销售产品码
        model.setProductCode("PRE_AUTH_ONLINE");

        // 设置收款账户的支付宝登录号（email或手机号）
        model.setPayeeLogonId("159****5620");

        // 设置无特殊需要请勿传入
        model.setEnablePayChannels("[{\"payChannelType\":\"PCREDIT_PAY\"},{\"payChannelType\":\"MONEY_FUND\"}]");

        // 设置免押受理台模式
        model.setDepositProductMode("POSTPAY");

        // 设置无特殊需要请勿传入
        model.setIdentityParams(
                "{\"identity_hash\":\"acc2b92ffc5ed9b472faa19748f10045c30434132784f774b00216a56b8841c6\"}");

        // 设置业务参数
        model.setBusinessParams(
                "{\"outRiskInfo\":\"{\"mcCreateTradeTime\":\"2022-03-11 12:46:09\",\"extraAccountCertnoLastSix\":\"000011\",\"mobileOperatingPlatform\":\"ios\",\"sysVersion\":\"15.4.2\",\"mcCreateTradeIp\":\"11.110.111.43\"}\"}");

        // 设置预授权订单相对超时时间
        model.setTimeoutExpress("2d");

        // 设置无特殊需要请勿传入
        model.setDisablePayChannels(
                "[{\"payChannelType\":\"OPTIMIZED_MOTO\"},{\"payChannelType\":\"BIGAMOUNT_CREDIT_CARTOON\"}]");

        // 设置商户本次资金操作的请求流水号
        model.setOutRequestNo("8077735255938032");

        // 设置业务扩展参数
        model.setExtraParam("{\"category\":\"CHARGE_PILE_CAR\",\"serviceId\":\"2020042800000000000001450466\"}");

        request.setBizModel(model);
        AlipayFundAuthOrderAppFreezeResponse response = alipayClient.sdkExecute(request);
        String orderStr = response.getBody();
        System.out.println(orderStr);

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            System.out.println(diagnosisUrl);
        }

        return R.ok();
    }

    // 创建一个芝麻免押的订单

    @ApiOperation("支付宝免押订单查询")
    @PostMapping("/select")
    public R<String> alipayselect() throws AlipayApiException {
        AlipayConfig conf = new AlipayConfig();
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
        AlipayFundAuthOperationDetailQueryModel model = new AlipayFundAuthOperationDetailQueryModel();

        // 设置需要查询的授权资金操作类型
        model.setOperationType("FREEZE");

        // 设置商户的授权资金订单号
        model.setOutOrderNo("8077735255938023");

        // 设置支付宝的授权资金操作流水号
        model.setOperationId("20140216010020006400");

        // 设置商户的授权资金操作流水号
        model.setOutRequestNo("20140216001001");

        // 设置支付宝授权资金订单号
        model.setAuthNo("2014021601002000640012345678");

        request.setBizModel(model);
        AlipayFundAuthOperationDetailQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }

        return R.ok();
    }

    @ApiOperation("支付宝免押订单取消")
    @PostMapping("/payslip")
    public R<String> payslip() throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "app_id",
                "your private_key", "json", "GBK", "alipay_public_key", "RSA2");

        // 创建一个取消支付授权操作的请求
        AlipayFundAuthOperationCancelRequest request = new AlipayFundAuthOperationCancelRequest();

        // 创建一个JSONObject对象，用于封装请求体
        JSONObject bizContent = new JSONObject();

        // out_order_no与auth_no选择其一传入即可
        bizContent.put("out_order_no", "outOrderNo123");
        // auth_no在授权冻结成功时返回参数中获得
        // bizContent.put("auth_no","2021081710002001640564315836");

        // out_request_no与operation_id选择其一传入即可
        // out_request_no与冻结流水号相同
        bizContent.put("out_request_no", "outRequestNo123");
        // bizContent.put("operation_id","20161012405744018102");

        // 商家对本次撤销操作的附言描述，长度不超过100个字母或50个汉字
        bizContent.put("remark", "撤销授权");

        // 设置整体请求参数
        request.setBizContent(bizContent.toString());

        // 使用execute方法发起请求
        AlipayFundAuthOperationCancelResponse response = alipayClient.execute(request);

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        return R.ok();
    }

    private static AlipayConfig getAlipayConfig() {

        String privateKey = "<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->";
        String alipayPublicKey = "<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId("<-- 请填写您的AppId，例如：2019091767145019 -->");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

    @ApiOperation("删除用户信息")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
    @DeleteMapping("/{userId}")
    public R<String> delete(@PathVariable Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            users.remove(userId);
            return R.ok();
        } else {
            return R.fail("用户不存在");
        }
    }
}

@ApiModel(value = "UserEntity", description = "用户实体")
@lombok.Data
class UserEntity {
    @ApiModelProperty("用户ID")
    private Integer userId;

    @ApiModelProperty("用户名称")
    private String username;

    @ApiModelProperty("用户密码")
    private String password;

    @ApiModelProperty("用户手机")
    private String mobile;

    public UserEntity() {

    }

    public UserEntity(Integer userId, String username, String password, String mobile) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.mobile = mobile;
    }
}
